package com.leyou.cart.interceptor;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * 用户信息拦截器，目的为了获取当前登录的用户信息
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private final static String USER_TOKEN = "LY_TOKEN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 获取token信息
            String ly_token = CookieUtils.getCookieValue(request, USER_TOKEN);
            // 获取token中的载荷
            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(ly_token, UserInfo.class);
            // 获取到用户信息
            UserInfo userInfo = infoFromToken.getUserInfo();
            // 把用户存入当前线程中
            UserHolder.setUser(userInfo);
            log.info("【购物车微服务】当前用户id：{}， 当前用户名称： {}，  用户角色：{}",userInfo.getId(),userInfo.getUsername(),userInfo.getRole());
            return true;
        } catch (UnsupportedEncodingException e) {
            log.error("【购物车微服务】解析用户token，并存入ThreadLocal出现异常：{}",e.getMessage());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除柜子的东西
        UserHolder.removeUser();
    }
}
